package lossy;

import java.awt.image.BufferedImage;


public class Threshold {

	public static double[][] performTreshold(double[][] in, int n, int tresholdValue){
		double[][] out = new double[n][n];
		BufferedImage image = new BufferedImage(1,1,BufferedImage.TYPE_BYTE_GRAY);
		int red = 0;
		int green = 0;
		int blue = 0;
                
		for(int i = 0; i < n; i++){
			for(int j = 0; j < n; j++){
                            image.setRGB(0, 0, (int)in[i][j]);
                            int color = image.getRGB(0, 0);
                            red = getRed(color);
                            green = getGreen(color);
                            blue = getBlue(color);
//                            if(((int)(Math.random()*1130)) == 23)
// System.out.println(in[i][j]+ " "+image.getRGB(0, 0)+" "+red+" "+green+" "+blue+" "+(red+green+blue)/3+" "+tresholdValue);
				if((red+green+blue)/3 < (int) tresholdValue){
					out[i][j] = mixColor(0,0,0);
				} else {
					out[i][j] = mixColor(255,255,255);
				}
			}
		}
		
		return out;
	}
	public static double[][] performThreshold(double[][] in, int n, int minTV){
		double[][] out = new double[n][n];
		int color;
		for(int i = 0; i < n; i++){
			for(int j = 0; j < n; j++){
				color = Math.abs((int) in[i][j]);
				if(color < minTV){
					out[i][j] = 0;
				} else {
					out[i][j] = in[i][j];
				}
			}
		}
		
		return out;
	}
		
	public static BufferedImage performThreshold(BufferedImage img, int requiredThresholdValue) {
		int height = img.getHeight();
		int width = img.getWidth();
		BufferedImage finalThresholdImage = new BufferedImage(width,height,BufferedImage.TYPE_BYTE_GRAY) ;
		
		int red = 0;
		int green = 0;
		int blue = 0;
		
		for (int x = 0; x < width; x++) {
			try {
				for (int y = 0; y < height; y++) {
					int color = img.getRGB(x, y);
					
					red = getRed(color);
					green = getGreen(color);
					blue = getBlue(color);
					
					if((red+green+blue)/3 < (int) (requiredThresholdValue)) {
						finalThresholdImage.setRGB(x,y, mixColor(0, 0,0));
					}
					else {
						finalThresholdImage.setRGB(x,y, mixColor(255, 255,255));
					}
				}
			} catch (Exception e) {
				 e.getMessage();
			}
		}
		
		return finalThresholdImage;
	}

	private static int mixColor(int red, int green, int blue) {
		return red<<16|green<<8|blue;
	}

	public static int getRed(int color) {
		return (color & 0x00ff0000)  >> 16;
	}
	
	public static int getGreen(int color) {
		return	(color & 0x0000ff00)  >> 8;
	}
	
	public static int getBlue(int color) {
		return (color & 0x000000ff)  >> 0;
		
	}
}
